package com.xy.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.a520it.generalutils.R;
import com.xy.debug.LogUtils;
import com.xy.debug.SystemConfig;


/**
 * Created by John on 2016/11/11.
 */

public class XyTabLayout extends HorizontalScrollView {


    private float tabTextSize;
    private int tabTextColor;
    private int tabSelectedTextColor;
    private int onScreenItem = 4;
    private Paint paint;
    private LinearLayout contentView;
    private String[] items;
    private int itemWidth;
    private ViewPager viewPager;
    private float indicaLoc;
    private int tabBackground;
    private int tabIndicatorColor;

    public XyTabLayout(Context context) {
        this(context, null);
    }

    public XyTabLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public XyTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.XyTabLayout);
        tabBackground = array.getColor(R.styleable.XyTabLayout_tab_background, Color.GRAY);
        tabIndicatorColor = array.getColor(R.styleable.XyTabLayout_tab_indicatorColor, Color.BLACK);
        tabSelectedTextColor = array.getColor(R.styleable.XyTabLayout_tab_selectedTextColor, Color.BLACK);
        tabTextColor = array.getColor(R.styleable.XyTabLayout_tab_textColor, Color.RED);
        tabTextSize = array.getDimensionPixelSize(R.styleable.XyTabLayout_tab_textSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics()));
        array.recycle();
        init(context);
    }

    private void init(Context context) {
        setHorizontalScrollBarEnabled(false);
        paint = new Paint();
        contentView = new LinearLayout(context);
        contentView.setOrientation(LinearLayout.HORIZONTAL);
        setBackgroundColor(tabBackground);
        addView(contentView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }

    public void setItems(String[] items) {
        this.items = items;
        addItemView();
        setItemClick();
    }

    public void addItemView() {
        if (items.length != 0) {
            for (int i = 0; i < items.length; i++) {
                TextView textView = new TextView(getContext());
                textView.setText(items[i]);
                //获取的是px还要转成sp
                textView.setTextSize(SystemConfig.px2sp(getContext(), (int) tabTextSize));
                textView.setGravity(Gravity.CENTER);
                textView.setClickable(true);
                textView.setTextColor(textView.isSelected() ? tabSelectedTextColor : tabTextColor);
                contentView.addView(textView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            }
        }
    }

    public void setItemClick() {
        final int count = contentView.getChildCount();
        for (int i = 0; i < count; i++) {
            final int finalI = i;
            final TextView text = (TextView) (contentView.getChildAt(i));
            text.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (viewPager != null) {
                        viewPager.setCurrentItem(finalI, true);
                        itemSelect(finalI);
                    }
                }
            });

        }
    }

    public void itemSelect(int index) {
        int count = contentView.getChildCount();
        for (int j = 0; j < count; j++) {
            TextView text = (TextView) contentView.getChildAt(j);
            text.setSelected(index == j);
            text.setTextColor(text.isSelected() ? tabSelectedTextColor : tabTextColor);
        }
    }

    private float positionOff;

    public void setViewPager(ViewPager viewPager) {
        this.viewPager = viewPager;
        this.viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {


            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                indicaLoc = itemWidth * (position + positionOffset);
                positionOff = positionOffset;
                smoothScrollTo((int) indicaLoc, 0);
                itemSelect(position);
                invalidate();
            }

            @Override
            public void onPageSelected(int position) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        if (this.items == null) {
            final PagerAdapter adapter = viewPager.getAdapter();
            adapter.registerDataSetObserver(new DataSetObserver() {
                @Override
                public void onChanged() {
                    super.onChanged();
                    setpageTittle(adapter);
                }
            });

        }
    }

    private void setpageTittle(PagerAdapter adapter) {
        String[] items = new String[adapter.getCount()];
        for (int i = 0; i < adapter.getCount(); i++) {
            items[i] = (String) adapter.getPageTitle(i);
        }
        setItems(items);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (items != null && items.length != 0) {
            int n = contentView.getChildCount();
            itemWidth = 0;
            if (n > onScreenItem) {
                itemWidth = (int) (SystemConfig.getScreenWidth(getContext()) / (onScreenItem + 0.5f));
            } else {
                itemWidth = SystemConfig.getScreenWidth(getContext()) / onScreenItem;
            }
            int itemHeight = getMeasuredHeight() * 9 / 10;
            contentView.measure(MeasureSpec.makeMeasureSpec(itemWidth * n, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(itemHeight, MeasureSpec.EXACTLY));
            for (int i = 0; i < items.length; i++) {
                contentView.getChildAt(i).measure(MeasureSpec.makeMeasureSpec(itemWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(itemHeight, MeasureSpec.EXACTLY));
            }
        }
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        paint.setColor(tabIndicatorColor);
        canvas.drawRect(indicaLoc, getMeasuredHeight() * 9 / 10, indicaLoc + itemWidth * (positionOff > 0.5 ? positionOff : 1 - positionOff), getMeasuredHeight(), paint);
    }

}
